#pragma once
#include "蛇和食物初始化.h"
#include<stdio.h>
#include<windows.h>
#include "移动函数.h"
#include <io.h>
#include <process.h>

int score = 0;//分数
int max_score = 0;//最高分
int speed = 400;
int speed_v = 0;

void game()
{
	
	int i;
	char key='d';
	char ch;

	COORD coord;
	getchar();

	while (1)
	{
		if (_kbhit())
		{
			ch= _getch();
			if (ch == 'q' || ch == 'Q')
			{
				if (speed >= 80)
				{
					speed -= 30;
					speed_v += 1;
					set(WIDE + 1, 3);
					printf("速度为:%d", speed_v);
				}
			}
			else if (ch == 'e' || ch == 'E')
			{
				speed += 30;
				speed_v -= 1;
				set(WIDE + 1, 3);
				printf("速度为:%d", speed_v);
			}
			else // 处理方向键		
				key = ch; // 仅方向键更新key			
		}					
		else
			move(key);

		//蛇头撞墙游戏结束
		if (snake.body[0].X <= 0 || snake.body[0].X >= WIDE
			|| snake.body[0].Y <= 0 || snake.body[0].Y >= HIGH)
		{
			set(mid1.X, mid2.Y);
			printf("*");
			set(0, HIGH + 2);
			FILE* fp1 = fopen("最高分.txt", "w");
			fprintf(fp1, "%d", max_score);
			return;
		}
		//蛇头撞身体游戏结束
		for (i = 1; i < snake.size; i++)
		{
			if (snake.body[0].X == snake.body[i].X && snake.body[0].Y == snake.body[i].Y)
			{
				set(0, HIGH + 2);
				FILE* fp1 = fopen("D:\\code\\VS\\eat_snake\\最高分.txt", "w");
				fprintf(fp1, "%d", max_score);
				return;
			}
		}
		//蛇吃到食物
		if (snake.body[0].X == food.X && snake.body[0].Y == food.Y)
		{
			snake.size++;
			score += 10;
			set(WIDE + 1, 1);
			printf("目前得分为:%d", score);
			if (speed >= 100)
			{
				speed -= 5;
				speed_v += 1;
				set(WIDE + 1, 3);
				printf("速度为:%d", speed_v);
			}
			if (score > max_score)
				max_score = score;
			initFood();
			set(food.X, food.Y);
			printf("#");
		}
		//如果蛇的下一步移动不会触发死亡，则画下一条蛇,并去除尾部多余的部分
		for (i = 0; i < snake.size; i++)
		{
			coord.X = snake.body[i].X;
			coord.Y = snake.body[i].Y;
			SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
			printf("*");
		}
		Sleep(speed);
	}
}
